package com.shopping.mall.core.module.goods.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping.mall.auth.exception.RedisTokenErrorException;
import com.shopping.mall.auth.exception.RedisTokenNullException;
import com.shopping.mall.auth.utils.JwtUtils;
import com.shopping.mall.core.module.attributeKey.entity.AttributeKey;
import com.shopping.mall.core.module.attributeKey.mapper.AttributeKeyMapper;
import com.shopping.mall.core.module.attributeValue.entity.AttributeValue;
import com.shopping.mall.core.module.attributeValue.mapper.AttributeValueMapper;
import com.shopping.mall.core.module.favorite.entity.Favorite;
import com.shopping.mall.core.module.favorite.mapper.FavoriteMapper;
import com.shopping.mall.core.module.goods.entity.Goods;
import com.shopping.mall.core.module.goods.mapper.GoodsMapper;
import com.shopping.mall.core.module.goods.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.mall.base.http.ResponseState;
import com.shopping.mall.base.http.Result;
import com.shopping.mall.base.util.WrapperUtils;
import com.shopping.mall.core.module.goods.vo.GoodsVo;
import com.shopping.mall.core.module.goodsSpecification.entity.GoodsSpecification;
import com.shopping.mall.core.module.goodsSpecification.mapper.GoodsSpecificationMapper;
import com.shopping.mall.core.module.goodsSpecification.service.GoodsSpecificationService;
import com.shopping.mall.core.module.saleData.service.SaleDataService;
import com.shopping.mall.core.module.type.entity.Type;
import com.shopping.mall.core.module.type.mapper.TypeMapper;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * Goods服务实现类
 * </p>
 *
 * @author zzy
 * @since 2021-08-13
 */
@Validated
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private AttributeKeyMapper attributeKeyMapper;
    @Autowired
    private AttributeValueMapper attributeValueMapper;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private Logger logger;
    @Autowired
    private SaleDataService saleDataService;
    @Autowired
    private GoodsSpecificationService goodsSpecificationService;

    /**
     * 获取随机商品
     *
     * @param n
     * @return
     */
    @Override
    public Result<Object> getRandomGoods(Integer n, HttpServletRequest request) {
        try {
            final List<Goods> goodsList = goodsMapper.getRandomGoods(n);
            String userId = null;
            //是否已登录,获取userId
            try {
                String token = request.getHeader("Authorization").split(" ")[1];
                userId = jwtUtils.getUserId(token);
            } catch (RedisTokenErrorException e) {
                logger.warn("refreshToken错误");
            } catch (RedisTokenNullException | ExpiredJwtException e) {
                logger.warn("refreshToken已过期");
            } catch (Exception e) {
                logger.error("发生错误:{}", e.getStackTrace());
            }
            loginUserFavorite(userId, goodsList);
            return Result.OK(goodsList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResponseState.ERROR.getValue(), ResponseState.ERROR.getMessage());
        }

    }

    /**
     * 按type查询(筛选)商品,分页返回
     *
     * @param typeId
     * @param current：页码
     * @param size：每页条数
     * @return
     */
    @Override
    @Deprecated
    public Result<Object> filtrateByType(String typeId, Integer current, Integer size, String text, HttpServletRequest request) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id",
                "name",
                "less_intro",
                "main_image",
                "price",
                "current_price",
                "fake_price",
                "producer").eq("status", 1);//正常售卖
        if (text != null) {
            queryWrapper.like("name", text);
        }
        String userId = null;
        //是否已登录,获取userId
        try {
            String token = request.getHeader("Authorization").split(" ")[1];
            userId = jwtUtils.getUserId(token);
        } catch (RedisTokenErrorException e) {
            logger.warn("refreshToken错误");
        } catch (RedisTokenNullException | ExpiredJwtException e) {
            logger.warn("refreshToken已过期");
        } catch (Exception e) {
            logger.error("发生错误:{}", e.getStackTrace());
        }
        Page<Goods> page = new Page<>(current, size);
        if (typeId == null) {//没有type筛选
            final IPage<Goods> goodsIPage = goodsMapper.selectPage(page, queryWrapper);
            loginUserFavorite(userId, goodsIPage.getRecords());
            return Result.OK(goodsIPage);
        }
        final Type type = typeMapper.selectById(typeId);
        if (type == null) {
            return Result.error(ResponseState.TARGET_NOT_EXIST.getValue(), ResponseState.TARGET_NOT_EXIST.getMessage());
        }
        final Integer level = type.getLevel();

        if (level == 1) {
            queryWrapper.eq("primary_type_id", typeId);
        } else if (level == 2) {
            queryWrapper.eq("secondary_type_id", typeId);
        } else if (level == 3) {
            queryWrapper.eq("tertiary_type_id", typeId);
        } else {
            return Result.error(ResponseState.PARENT_NOT_EXIST.getValue(), ResponseState.PARENT_NOT_EXIST.getMessage());
        }
        final IPage<Goods> goodsIPage = goodsMapper.selectPage(page, queryWrapper);
        loginUserFavorite(userId, goodsIPage.getRecords());
        return Result.OK(goodsIPage);
    }

    /**
     * 判断商品是否已被收藏
     *
     * @param userId
     * @param goodsList
     */
    private void loginUserFavorite(String userId, List<Goods> goodsList) {
        QueryWrapper<Favorite> favoriteQueryWrapper = new QueryWrapper<>();
        favoriteQueryWrapper.eq("user_id", userId);
        final List<Favorite> favoriteList = favoriteMapper.selectList(favoriteQueryWrapper);
        goodsList.forEach(goods -> {
            final boolean isFavorite = favoriteList.stream().map(Favorite::getGoodsId).anyMatch(goodsId -> goodsId.equals(goods.getId()));
            goods.setFavorite(isFavorite);
        });
    }

    private void specificationOnlyOne(List<Goods> goodsList) {
        QueryWrapper<GoodsSpecification> specificationQueryWrapper = new QueryWrapper<>();
        specificationQueryWrapper.in("goods_id", goodsList.stream().map(Goods::getId).collect(Collectors.toList()));
        final List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectList(specificationQueryWrapper);
        //替换json
        final Iterator<GoodsSpecification> it = goodsSpecifications.iterator();
        while (it.hasNext()) {
            final GoodsSpecification goodsSpecification = it.next();
            try {
                final String specification = goodsSpecification.getSpecification();
                final List<Map> specifications = JSON.parseArray(specification, Map.class);
                specifications.forEach(map -> {
                    final Object key = map.get("key");
                    final Object value = map.get("value");
                    String attributeKey;
                    String attributeValue;
                    attributeKey = attributeKeyMapper.selectById(String.valueOf(key)).getAttributeKey();
                    attributeValue = attributeValueMapper.selectById(String.valueOf(value)).getAttributeValue();
//                    System.out.println("key:" + attributeKey + "  value:" + attributeValue);

                    map.replaceAll((k, v) -> {
                        if (String.valueOf(k).equals("key")) {
                            return attributeKey;
                        } else if (String.valueOf(k).equals("value")) {
                            return attributeValue;
                        } else {
                            return v;
                        }
                    });
                });
                final String s = JSON.toJSONString(specifications);
                goodsSpecification.setSpecification(s);
            } catch (Exception e) {
                final String id = goodsSpecification.getId();
                goodsSpecificationService.deleteById(id);
//                System.out.println("删除了无效规格");
                it.remove();
                logger.error(Arrays.toString(e.getStackTrace()));
                continue;
            }
                goodsSpecificationService.goodsUpdate(goodsSpecification.getGoodsId());
        }
        //将goodsSpecification赋给goods
        goodsList.forEach(goods -> {
            final List<GoodsSpecification> filterGoodsSpecifications = goodsSpecifications.stream().filter(goodsSpecification -> goodsSpecification.getGoodsId().equals(goods.getId())).collect(Collectors.toList());
            goods.setGoodsSpecifications(filterGoodsSpecifications);
            if (filterGoodsSpecifications.size() == 1) {
                if (goods.getGoodsSpecifications() != null) {
                    if (goods.getGoodsSpecifications().get(0) != null) {
                        goods.setType(goods.getGoodsSpecifications().get(0).getType());
                    }
                }
            }

            if (filterGoodsSpecifications.size() != 1) {
                if (goods.getSpecification() != null) {
                    goods.setType(null);
                    goods.getSpecification().setType(null);
                }
                goods.setPrice(null);
                goods.setCurrentPrice(null);
                goods.setStock(null);
            }
        });
    }

    /**
     * 管理员按type查询(筛选)商品,分页返回
     *
     * @param typeId  :    商品id
     * @param current ：页码
     * @param size    ：每页条数
     * @param text    :      搜索信息
     * @return
     */
    @Override
    public Result<Object> filtrateByTypeAdmin(String typeId, Integer current, Integer size, String text) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (text != null) {
            queryWrapper.like("name", text);
        }
        Page<Goods> page = new Page<>(current, size);
        if (typeId == null) {
            final IPage<Goods> goodsIPage = goodsMapper.selectPage(page, queryWrapper);
            final List<Goods> records = goodsIPage.getRecords();
            if (!records.isEmpty()) {
                specificationOnlyOne(records);
            }
            return Result.OK(goodsIPage);
        }
        final Type type = typeMapper.selectById(typeId);
        if (type == null) {
            return Result.error(ResponseState.TARGET_NOT_EXIST.getValue(), ResponseState.TARGET_NOT_EXIST.getMessage());
        }
        final Integer level = type.getLevel();

        if (level == 1) {
            queryWrapper.eq("primary_type_id", typeId);
            final IPage<Goods> goodsIPage = goodsMapper.selectPage(page, queryWrapper);
            final List<Goods> records = goodsIPage.getRecords();
            if (!records.isEmpty()) {
                specificationOnlyOne(records);
            }
            return Result.OK(goodsIPage);
        } else if (level == 2) {
            queryWrapper.eq("secondary_type_id", typeId);
            final IPage<Goods> goodsIPage = goodsMapper.selectPage(page, queryWrapper);
            final List<Goods> records = goodsIPage.getRecords();
            if (!records.isEmpty()) {
                specificationOnlyOne(records);
            }
            return Result.OK(goodsIPage);
        } else if (level == 3) {
            queryWrapper.eq("tertiary_type_id", typeId);
            final IPage<Goods> goodsIPage = goodsMapper.selectPage(page, queryWrapper);
            final List<Goods> records = goodsIPage.getRecords();
            if (!records.isEmpty()) {
                specificationOnlyOne(records);
            }
            return Result.OK(goodsIPage);
        } else {
            return Result.error(ResponseState.PARENT_NOT_EXIST.getValue(), ResponseState.PARENT_NOT_EXIST.getMessage());
        }
    }

    /**
     * 按type查询(筛选)商品,不分页
     *
     * @param typeId
     * @param text
     * @return
     */
    @Override
    public Result<Object> filtrateByType(String typeId, String text, HttpServletRequest request) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id",
                "name",
                "less_intro",
                "main_image",
                "price",
                "current_price",
                "fake_price"
        ).eq("status", 1);//正常售卖
        if (text != null) {
            queryWrapper.like("name", text);
        }
        if (typeId == null) {
            final List<Goods> goods = goodsMapper.selectList(queryWrapper);
            return Result.OK(goods);
        }
        final Type type = typeMapper.selectById(typeId);
        if (type == null) {
            return Result.error(ResponseState.TARGET_NOT_EXIST.getValue(), ResponseState.TARGET_NOT_EXIST.getMessage());
        }
        final Integer level = type.getLevel();
        if (level == 1) {
            queryWrapper.eq("primary_type_id", typeId);
            final List<Goods> goods = goodsMapper.selectList(queryWrapper);
            return Result.OK(goods);
        } else if (level == 2) {
            queryWrapper.eq("secondary_type_id", typeId);
            final List<Goods> goods = goodsMapper.selectList(queryWrapper);
            return Result.OK(goods);
        } else if (level == 3) {
            queryWrapper.eq("tertiary_type_id", typeId);
            final List<Goods> goods = goodsMapper.selectList(queryWrapper);
            return Result.OK(goods);
        } else {
            return Result.error(ResponseState.PARENT_NOT_EXIST.getValue(), ResponseState.PARENT_NOT_EXIST.getMessage());
        }
    }

    /**
     * 商品信息
     *
     * @param id
     * @param request
     * @return
     */
    @Override
    public Result<Object> goodsInfo(String id, HttpServletRequest request) {
        final List<Goods> goods = goodsMapper.getGoodWithSpecificationById(List.of(id));
        if (goods == null) {
            return Result.error(ResponseState.TARGET_NOT_EXIST.getValue(), ResponseState.TARGET_NOT_EXIST.getMessage());
        }
        QueryWrapper<GoodsSpecification> specificationQueryWrapper = new QueryWrapper<>();
        //载入商品页面是就缓存规格信息
        //生成订单时再次发送请求,返回价格
        specificationQueryWrapper.eq("goods_id", id);
        final List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectList(specificationQueryWrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("goods", goods);
        if (goodsSpecifications.isEmpty()) {
            data.put("goodsSpecifications", null);
        } else {
            data.put("goodsSpecifications", goodsSpecifications);
            //价格区间,最高价和最低价(打折后)
            final Optional<Double> maxOptional = goodsSpecifications.stream().map(GoodsSpecification::getDiscountPrice).max(Comparator.comparingDouble(i -> i));
            if (maxOptional.isPresent()) {
                data.put("maxPrice", maxOptional.get());
            } else {
                data.put("maxPrice", null);
            }
            final Optional<Double> minOptional = goodsSpecifications.stream().map(GoodsSpecification::getDiscountPrice).min(Comparator.comparingDouble(i -> i));
            if (minOptional.isPresent()) {
                data.put("minPrice", minOptional.get());
            } else {
                data.put("minPrice", null);
            }
        }

        //是否已收藏
        try {
            String token = request.getHeader("Authorization").split(" ")[1];
            final String userId = jwtUtils.getUserId(token);
            QueryWrapper<Favorite> favoriteQueryWrapper = new QueryWrapper<>();
            favoriteQueryWrapper.eq("user_id", userId).eq("goods_id", id);
            final Integer i = favoriteMapper.selectCount(favoriteQueryWrapper);
            if (i == 0) {
                data.put("isFavorite", false);
            } else {
                data.put("isFavorite", true);
            }
        } catch (RedisTokenErrorException e) {
            logger.warn("refreshToken错误");
            data.put("isFavorite", false);
        } catch (RedisTokenNullException | ExpiredJwtException e) {
            logger.warn("refreshToken已过期");
            data.put("isFavorite", false);
        } catch (Exception e) {
            logger.error("发生错误:{}", e.getStackTrace());
            data.put("isFavorite", false);
        }
        saleDataService.visit();
        return Result.OK(data);
    }

    /**
     * 分页查询
     *
     * @param current：页码
     * @param size：每页条数
     * @param goods：筛选条件
     * @return IPage<Goods>
     */
    @Override
    public IPage<Goods> getGoodsPage(Integer current, Integer size, Goods goods) {
        QueryWrapper<Goods> queryWrapper = WrapperUtils.queryWrapper(goods);
        Page<Goods> goodsPage = new Page<>(current, size);
        IPage<Goods> goodsIPage = goodsMapper.selectPage(goodsPage, queryWrapper);
        return goodsIPage;
    }

    /**
     * 查询所有
     *
     * @param goods：筛选条件
     * @return List<Goods>
     */
    @Override
    public List<Goods> getAll(Goods goods) {
        QueryWrapper<Goods> queryWrapper = WrapperUtils.queryWrapper(goods);
        return goodsMapper.selectList(queryWrapper);
    }

    /**
     * 添加商品
     *
     * @param goods
     * @return
     */
    @Override
    @Transactional
    public Result<Object> add(Goods goods) {
        goods.setStatus(0);
        final List<String> subImageList = goods.getSubImageList();
        final String subImages = JSON.toJSONString(subImageList);
        goods.setSubImages(subImages);
        goodsMapper.insert(goods);
        final String goodsId = goods.getId();
        final List<AttributeKey> specificationList = goods.getSpecificationList();
        specificationList.forEach(attributeKey -> {
            attributeKey.setId(null);
            attributeKey.setGoodsId(goodsId);
            final int i = attributeKeyMapper.insert(attributeKey);
            if (i == 0) {
                logger.error("添加失败");
                throw new RuntimeException("添加规格key失败,事务回滚");
            }
            final String attributeKeyId = attributeKey.getId();
            final List<AttributeValue> attributeValueList = attributeKey.getAttributeValueList();
            attributeValueList.forEach(attributeValue -> {
                attributeValue.setId(null);
                attributeValue.setAttributeId(attributeKeyId);
                final int i1 = attributeValueMapper.insert(attributeValue);
                if (i1 == 0) {
                    logger.error("添加失败");
                    throw new RuntimeException("添加规格value失败,事务回滚");
                }
            });
        });
        return Result.OK(goodsId);
    }

    /**
     * 商品和规格一起添加
     *
     * @param goodsVo
     * @return
     */
    @Override
    @Transactional
    public Result<Object> addGoodsWithSpecification(GoodsVo goodsVo) {
        try {
            add(goodsVo.getGoods());
            final List<AttributeKey> specificationList = goodsVo.getGoods().getSpecificationList();
            final Map<String, List<AttributeKey>> keyFlagIdMap = specificationList.stream().collect(Collectors.groupingBy(AttributeKey::getFlagId));
            List<AttributeValue> attributeValueList = new ArrayList<>();
            specificationList.forEach(specification -> attributeValueList.addAll(specification.getAttributeValueList()));
            final Map<String, List<AttributeValue>> valueFlagIdMap = attributeValueList.stream().collect(Collectors.groupingBy(AttributeValue::getFlagId));
            goodsVo.getGoodsSpecificationVoList().forEach(goodsSpecificationVo -> {
                goodsSpecificationVo.setGoodsId(goodsVo.getGoods().getId());
                goodsSpecificationVo.getSpecification().forEach(specificationMap -> {
                    specificationMap.replaceAll((k, v) -> {
                        if (String.valueOf(k).equals("key")) {
                            return keyFlagIdMap.get(specificationMap.get("key")).get(0).getId();
                        } else if (String.valueOf(k).equals("value")) {
                            return valueFlagIdMap.get(specificationMap.get("value")).get(0).getId();
                        } else {
                            return v;
                        }
                    });
                });
                goodsSpecificationService.addGoodsSpecification(goodsSpecificationVo);
            });
            return Result.OK(goodsVo.getGoods().getId());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加失败,事务回滚");
            throw new RuntimeException("添加失败");
        }
    }

    /**
     * 修改商品信息
     *
     * @param goods
     * @return
     */
    @Override
    @Transactional
    public Result<Object> changeGoods(Goods goods) {
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        final List<String> subImageList = goods.getSubImageList();
        final String subImages = JSON.toJSONString(subImageList);
        goods.setSubImages(subImages);
        updateWrapper.eq("id", goods.getId());
        final int i = goodsMapper.update(goods, updateWrapper);
        if (i == 0) {
            logger.error("更新失败");
            return Result.error(ResponseState.ERROR.getValue(), ResponseState.ERROR.getMessage());
        }
        final List<AttributeKey> specificationList = goods.getSpecificationList();
        if (specificationList.isEmpty()) {
            return Result.OK();
        }
        List<String> attributeKeyNotDeleteIds = new ArrayList<>();
        QueryWrapper<AttributeKey> attributeKeyDeleteWrapper = new QueryWrapper<>();
        List<String> attributeValueNotDeleteIds = new ArrayList<>();
        QueryWrapper<AttributeValue> attributeValueDeleteWrapper = new QueryWrapper<>();
        specificationList.forEach(attributeKey -> {
            if (attributeKey.getId() != null) {
                final int i1 = attributeKeyMapper.updateById(attributeKey);
                if (i1 == 0) {
                    logger.error("key更新失败");
                    throw new RuntimeException("更新规格key失败,事务回滚");
                }
                final List<AttributeValue> attributeValueList = attributeKey.getAttributeValueList();
                attributeValueList.forEach(attributeValue -> {
                    if (attributeValue.getId() != null) {
                        final int i2 = attributeValueMapper.updateById(attributeValue);
                        if (i2 == 0) {
                            logger.error("value更新失败");
                            throw new RuntimeException("更新规格value失败,事务回滚");
                        }
                    } else {
                        attributeValue.setAttributeId(attributeKey.getId());
                        final int i2 = attributeValueMapper.insert(attributeValue);
                        if (i2 == 0) {
                            logger.error("添加value失败");
                            throw new RuntimeException("添加规格value失败,事务回滚");
                        }
                    }
                    attributeValueNotDeleteIds.add(attributeValue.getId());
                });
            } else {
                attributeKey.setGoodsId(goods.getId());
                final int i1 = attributeKeyMapper.insert(attributeKey);
                if (i1 == 0) {
                    logger.error("添加key失败");
                    throw new RuntimeException("添加规格key失败,事务回滚");
                }
                attributeKeyNotDeleteIds.add(attributeKey.getId());
                final String attributeKeyId = attributeKey.getId();
                final List<AttributeValue> attributeValueList = attributeKey.getAttributeValueList();
                attributeValueList.forEach(attributeValue -> {
                    attributeValue.setAttributeId(attributeKeyId);
                    final int i2 = attributeValueMapper.insert(attributeValue);
                    if (i2 == 0) {
                        logger.error("添加失败");
                        throw new RuntimeException("添加规格value失败,事务回滚");
                    }
                    attributeValueNotDeleteIds.add(attributeValue.getId());
                });
            }
            attributeKeyNotDeleteIds.add(attributeKey.getId());
        });
        attributeKeyDeleteWrapper.eq("goods_id", goods.getId()).notIn("id", attributeKeyNotDeleteIds);
        attributeValueDeleteWrapper.notIn("id", attributeValueNotDeleteIds).in("attribute_id", attributeKeyNotDeleteIds);
        final int deleteKeyCount = attributeKeyMapper.delete(attributeKeyDeleteWrapper);
        final int deleteValueCount = attributeValueMapper.delete(attributeValueDeleteWrapper);
        logger.info("删除了{}行key", deleteKeyCount);
        logger.info("删除了{}行value", deleteValueCount);

        final List<Goods> updatedGoods = goodsMapper.getGoodWithSpecificationById(List.of(goods.getId()));
        if (updatedGoods == null) {
            return Result.error(ResponseState.TARGET_NOT_EXIST.getValue(), ResponseState.TARGET_NOT_EXIST.getMessage());
        }
//        QueryWrapper<GoodsSpecification> specificationQueryWrapper = new QueryWrapper<>();
//        specificationQueryWrapper.eq("goods_id", goods.getId());
//        final List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectList(specificationQueryWrapper);
//        if (goodsSpecifications.isEmpty()) {
//            return Result.error(ResponseState.SPECIFICATION_NOT_EXIST.getValue(), ResponseState.SPECIFICATION_NOT_EXIST.getMessage());
//        }
        Map<String, Object> data = new HashMap<>();
        data.put("goods", updatedGoods);
//        data.put("goodsSpecifications", goodsSpecifications);
        return Result.OK(data);
    }

    /**
     * 修改商品status
     *
     * @param goods
     * @return
     */
    @Override
    public Result<Object> changeGoodsStatus(Goods goods) {
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", goods.getId());
        goodsMapper.update(goods, updateWrapper);
        return Result.OK();
    }

    /**
     * 通过id删除
     *
     * @param id：goodsId
     * @return Result<Object>
     */
    @Override
    @Transactional
    public Result<Object> deleteById(String id) {
        Goods goods = goodsMapper.selectById(id);
        if (goods == null) {
            return Result.error(ResponseState.TARGET_NOT_EXIST.getValue(), ResponseState.TARGET_NOT_EXIST.getMessage());
        }
        QueryWrapper<AttributeKey> attributeKeyQueryWrapper = new QueryWrapper<>();
        attributeKeyQueryWrapper.eq("goods_id", id);
        final List<AttributeKey> attributeKeyList = attributeKeyMapper.selectList(attributeKeyQueryWrapper);
        if (!attributeKeyList.isEmpty()) {
            QueryWrapper<AttributeValue> attributeValueQueryWrapper = new QueryWrapper<>();
            attributeKeyList.forEach(attributeKey ->
                    attributeValueQueryWrapper.eq("attribute_id", attributeKey.getId()).or()
            );
            final int i1 = attributeValueMapper.delete(attributeValueQueryWrapper);
            logger.info("删除了{}行value", i1);
        }
        QueryWrapper<GoodsSpecification> goodsSpecificationQueryWrapper = new QueryWrapper<>();
        goodsSpecificationQueryWrapper.eq("goods_id", id);
        final int i2 = attributeKeyMapper.delete(attributeKeyQueryWrapper);
        logger.info("删除了{}行key", i2);
        final int i3 = goodsSpecificationMapper.delete(goodsSpecificationQueryWrapper);
        logger.info("删除了{}行规格", i3);
        final int i4 = goodsMapper.deleteById(id);
        logger.info("删除了{}行商品", i4);
        return Result.OK();
    }

    /**
     * 批量删除
     *
     * @param ids：id列表
     * @return Result<Object>
     */
    @Override
    public Result<Object> batchDelete(List<String> ids) {
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids);
        goodsMapper.delete(updateWrapper);
        return Result.OK();
    }
}